

#include "WLevel.h"
#include "Asteroid.h"
#include "World.h"
#include "Configuration.h"
#include "Planet.h"

static const double LIMIT = 500.0;

Level::Level(World *world, const int number)
: min(-LIMIT,-LIMIT,-LIMIT), max(LIMIT,LIMIT,LIMIT), startPosition(0,0,0), number(number)
{
	this->world=world;
	timeElapsed = 0.0;
	respawnStep = 0.5; timeNextRespawn = 0.0; spawnPlanetTime = 0.0; spawnPlanetFreq = 4000.0;
	
	minNumberOfEnemies = 300*number; 
	maxNumberOfEnemies = minNumberOfEnemies + 300;
	
	//number=1;
	
	objective=new WTarget(Point3d(0,0,-100));
	enemiesForGeneration= 80+number;
	generated=false;
	
	srand((unsigned)time(NULL));
}

Level*
Level::nextLevel(){
	return Level::getLevel(number+1, this->world);
}

void Level::step(const double tau) {
	
	if ( spawnPlanetFreq*tau < timeElapsed - spawnPlanetTime ) {
		spawnPlanetTime = timeElapsed;
		Planet * planet = new Planet(world->getPlayer()->position() + world->getPlayer()->velocity()*700.0/world->getPlayer()->velocity().norm() , 350.0, 150.0);
		Configuration::getInstance()->renderer->setUpPlanet(planet);
		world->addSlowObject(planet);
		
	}
	
	if ( timeElapsed >= timeNextRespawn && world->getNumberOfEnemies() < minNumberOfEnemies || !generated ) {
		unsigned int maxNumberOfEnemiesTmp=generated?maxNumberOfEnemies:enemiesForGeneration;
		
		generated=maxNumberOfEnemiesTmp>minNumberOfEnemies;
		
		for(unsigned int i = world->getNumberOfEnemies(); i < maxNumberOfEnemiesTmp; i++){
			Point3d pos=this->world->getPlayer()->position();
			
			
			
			double theta=((double(rand())/RAND_MAX)*3.1416);
			double phi=((double(rand())/RAND_MAX)*2.0*3.1416);
			double r=((double(rand())/RAND_MAX)*100)+300.0;
			
			pos+=Point3d(r*sin(theta)*cos(phi),r*sin(theta)*sin(phi),r*cos(theta));
			
			Point3d vel = world->getPlayer()->position() - pos;
			vel.normalize();
			const double radius = 0.05 + ((double(rand())/RAND_MAX)*12.8);
			const double mass = 2.0 + ((double(rand())/RAND_MAX)*7.0);
			const double speed = number/2.0 + ((double(rand())/RAND_MAX)*3.0);
			Asteroid * asteroid = new Asteroid(pos, speed*vel, mass, radius);
			asteroid->setStrength(mass*5.0);
			asteroid->setLife(mass*5.0);
			Configuration::getInstance()->renderer->setUpAsteroid(asteroid);
			world->addSlowObject(asteroid);
		}
		timeNextRespawn = timeElapsed + respawnStep;
	} 
	timeElapsed += tau;
}